/**
 *
 * @url websocket路径
 * @webSocketError 错误次数
 * @callback 回调
 * date：2020-12-14
 * author: Messi10
 *
 */
class WebSocketClass {
	constructor(url, webSocketError, callback) {
		this.instance = null
		this.callback = callback
		this.wsurl = url
		this.webSocketError = webSocketError
		this.webSocketErrorMax = 30
		this.ceshiCount = 0
		this.socketInit(url)
	}
	static getInstance() {
		if (!this.instance) {
			this.instance = new WebSocketClass()
		}
		return this.instance
	}
	// Socket初始化
	socketInit(url) {
		let xxx = null
		if (url != undefined) {
			// this.ws = uni.connectSocket({
			// 	url: url //仅为示例，并非真实接口地址。
			// });
			this.ws = uni.connectSocket({
				url, // 仅为示例，并非真实接口地址。
				success(data) {
					// console.log('websocket连接成功', data);
				}
			})
			// 监听 WebSocket 连接打开事件
			this.ws.onOpen(e => {
				this.status = 'open'
				this.ceshiCount++
				// console.log(`连接成功11`, e);
				this.getMessage()
			})
			// 监听 WebSocket 连接关闭事件
			this.ws.onClose(msg => {
				console.log(msg, 'oncloseonclose')
				if (this.webSocketError < this.webSocketErrorMax) {
					setTimeout(() => {
						this.socketInit(this.wsurl) // 重连
					}, 1000)
				} else {
					console.log('组件销毁或者重连数次过多')
				}
			})
			// 监听 WebSocket 错误事件
			this.ws.onError(err => {
				this.ceshiCount = 0
				this.webSocketError++
				console.log(err, this.ceshiCount, 'onerrorasdnt')
			})

		}
	}
	// Socket发送数据数据
	setSend(data) {

		console.log('setSend', data)
		this.ws.send({
			data,
			success: res => {
				// console.log('发送数据数据成功', res);
			}
		})

	}
	// 获取Socket数据
	getMessage() {
		this.ws.onMessage(e => {
			console.log('e', e)
			this.callback(e)
		})
	}

	// 关闭Socket
	close() {
		this.status = 'close'
		this.ws.send('close')
		this.webSocketError = 89
		this.ws.close()
	}
}
export default WebSocketClass
